package com.zxd.interview.cocurrent;


/**
 * 摘录自：https://stackoverflow.com/questions/24376768/can-java-finalize-an-object-when-it-is-still-in-scope%EF%BC%89
 * jdk8 存在的一个bug，对象在作用域内依然触发了垃圾回收的操作
 *
 * @author zhaoxudong
 * @version v1.0.0
 * @Package : com.zxd.interview.cocurrent
 * @Description : 验证终结方法是否会被优化
 * @Create on : 2022/1/11 14:11
 **/
public class FinalizeTest {

    @Override
    protected void finalize() {
        System.out.println(this + " was finalized!");
    }

    public static void main(String[] args) {
        FinalizeTest a = new FinalizeTest();
        System.out.println("Created " + a);
        for (int i = 0; i < 1_000_000_000; i++) {
            if (i % 1_000_000 == 0) {
                System.gc();
            }
        }
         System.out.println(a + " was still alive.");
    }/*
    不放开注释：
    Created com.zxd.interview.cocurrent.FinalizeTest@c4437c4
    FinalizeTest@c4437c4 was finalized!
    放开注释：
    Created com.zxd.interview.cocurrent.FinalizeTest@c4437c4
    com.zxd.interview.cocurrent.FinalizeTest@c4437c4 was still alive.
    */


}
